<?php

namespace App\Models;

use App\Constant\Compatible;
use App\Facades\CommonPlatformRequestFacade;
use App\Library\Bank\BankCode;
use App\Library\Guzzle\Sign;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

/**
 * App\Models\UserBankCard
 *
 * @property int $id
 * @property int $uid 用户id
 * @property string $card_username 持卡人姓名
 * @property string $card_num 银行卡号码，通常19位
 * @property string $phone_num 银行卡预留手机号
 * @property string $bank_name 银行卡名称
 * @property string $bank_name_show 银行展示名称
 * @property mixed $bank_code 银行编码
 * @property int $is_credit 是否是信用卡:1是2否3未知类型
 * @property string $hold_agreement_num 协议号
 * @property string $order_num 请求编号
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard whereBankCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard whereBankName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard whereBankNameShow($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard whereCardNum($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard whereCardUsername($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard whereHoldAgreementNum($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard whereIsCredit($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard whereOrderNum($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard wherePhoneNum($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard whereUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard whereUpdatedAt($value)
 * @mixin \Eloquent
 * @property string|null $old_kskd_user_id
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserBankCard whereOldKskdUserId($value)
 */
class UserBankCard extends Model
{


    /**
     * 是否是信用卡
     */
    const CREDIT_YES = 1;

    /**
     * 非信用卡
     */
    const CREDIT_NO = 2;

    /**
     * 未知类型
     */
    const CREDIT_UNKNOWN = 3;

    /**
     * 银行卡类型文本
     */
    const CARD_TYPE_TEXT = [
        self::CREDIT_YES => '信用卡',
        self::CREDIT_NO => '储蓄卡',
        self::CREDIT_UNKNOWN => '未知类型',
    ];

    const VALID_YES = 1;

    const VALID_NO = 0;

    /**
     * 定义不允许自动填充的字段
     * @var array
     */
    protected $guarded = [
        'id',
    ];


    /**
     * Description:获取有效的银行卡
     * Author: liuju
     * DateTime: 2019-03-05 17:04
     * @param $query
     * @return mixed
     */
    public function scopeValid($query)
    {
        return $query->where('is_valid',self::VALID_YES);
    }

    /**
     * Description:获取银行编码
     * Author: liuju
     * DateTime: 2019-01-04 19:48
     * @return mixed
     */
    public  function getBankCodeAttribute()
    {
        return BankCode::getBankCode($this->bank_name);
    }

    /**
     * Description:获取银行编码
     * Author:
     * DateTime: 2019-01-04 19:48
     * @return mixed
     */
    public  function getRealCodeAttribute()
    {
        return $this->bank_code;
    }


    public static function getCardInfoByCardNum($cardNum)
    {
        return self::where('card_num',$cardNum)->first();
    }

    /**
     * Description: 通过type字符来判定银行卡是否为信用卡
     * Author: liuju
     * DateTime: 2019-01-03 16:47
     * @param $type
     * @return int
     */
    public static function isCredit($type)
    {
        $val = self::CREDIT_UNKNOWN;
        $type = strtoupper($type);
        if ($type === 'Y') {
            $val = self::CREDIT_YES;
        } else if ($type === 'N') {
            $val = self::CREDIT_NO;
        }
        return $val;
    }

    /**
     * Description: cardType
     * Author: cg
     * DateTime: 2019-04-17 04:47
     * @param $type
     * @return int
     */
    public static function cardType($type)
    {
        if($type == ''){
            return self::CREDIT_NO;
        }
        $val = self::CREDIT_YES;
        if($type === 'N'){
            $val = self::CREDIT_NO;
        }
        return $val;
    }


    /**
     * Description: 通过类型获取银行卡类型文本
     * Author: liuju
     * DateTime: 2019-01-04 11:31
     * @param $typeId
     * @return mixed|string
     */
    public static function getCardType($typeId)
    {
        return !empty(self::CARD_TYPE_TEXT[$typeId]) ? self::CARD_TYPE_TEXT[$typeId] : '未知类型';
    }


    /**
     * Description: app端格式化银行卡信息
     * Author: liuju
     * DateTime: 2019-01-04 11:34
     * @param $data
     * @return mixed
     */
    public static function appFormat($data)
    {

        //获取银行卡类型文字信息
        if (!empty($data['is_credit'])) {
            $data['card_type'] = self::getCardType($data['is_credit']);
        }
        return $data;
    }

    /**
     * Description:通过id获取银行的协议号
     * Author:lijiafei
     * @param $id
     * @param $summary_id
     * @return mixed
     */
    public static function getHoldAgreementNumById($id,$summary_id){
        $userBankCard = UserBankCard::select('hold_agreement_num','uid') -> where('id',$id)->first();
        $summaryInfo = RepaySummary::select(['data_type','id'])->where('id',$summary_id)->first();
        if(empty($userBankCard)){
            return false;
        }
        $hold_agreement_num = $userBankCard->hold_agreement_num;
        if($summaryInfo->data_type == RepaySummary::DATA_TYPE_ONE){

            if(!$hold_agreement_num){
                return false;
            }
            //判断银行卡的协议号是否有效
            $res = CommonPlatformRequestFacade::checkHoldAgreement($hold_agreement_num);
            if ($res['code'] !== '01') {
                Log::debug('还款:验证银行协议号失败:' . 'id:' . $id . '协议号:' . $hold_agreement_num . ',返回数据' . json_encode($res,JSON_UNESCAPED_UNICODE));
                return false;
            }
            return $hold_agreement_num;

        }elseif($summaryInfo->data_type == RepaySummary::DATA_TYPE_TWO){
            //老的数据不进行验证
            if(!empty($hold_agreement_num)){
                return $hold_agreement_num;
            }else{
                //没有协议号,判断当前用户的其他卡是否有协议号
                $otherBank = UserBankCard::select('id')
                    ->where('uid',$userBankCard->uid)
                    ->where('hold_agreement_num','<>','')
                    ->whereNotNull('hold_agreement_num')
                    ->first();
                if(empty($otherBank->id)){
                    return true;
                }else{
                    //提示让用户换卡
                    return false;
                }
            }
        }

    }

    /**
     * 通过银行卡id获取银行卡的信息
     */
    public static function getCardInfoByBankCardId($bank_cards_id){
        $info = self::select('id','bank_name','is_credit','card_num','bank_name_show')->where('id',$bank_cards_id) -> first();
        if($info){
            $info = $info->toArray();
            if(isset($info['card_num'])){
                $info['card_num'] = substr($info['card_num'],-4);
            }
            $info['card_type'] = self::getCardType($info['is_credit']);
            unset($info['is_credit']);
            $icon_info = AdminBankIcon::select('icon_oss_url','single_limit','day_limit')->where('bank_name',$info['bank_name'])->first();
            if(empty($icon_info)){
                $icon_info = AdminBankIcon::select('icon_oss_url','single_limit','day_limit')->where('bank_name','其他')->first();
            }
            $info['icon_oss_url'] = isset($icon_info->ali_oss_full_url) ? $icon_info->ali_oss_full_url : '';
            $info['single_limit'] = isset($icon_info->single_limit) && $icon_info->single_limit > 0 ? '单笔限额' . $icon_info->single_limit . '元' : '';
            $info['day_limit'] = isset($icon_info->day_limit) && $icon_info->day_limit > 0 ? '单日限额' . $icon_info->day_limit . '元' : '';
        }

        return $info;
    }

    /**
     * id to card_num
     */
    public static function getCardNumById($bank_cards_id){
        return self::where('id',$bank_cards_id)->value('card_num');
    }



}
